package com.hmdp.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.ThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;


@Component
@RequiredArgsConstructor
@Slf4j
/**
 *此拦截器负责登入校验拦截,只拦截要进行登入的请求
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.放行非访问controller的请求
        if (!(handler instanceof HandlerMethod)) {
            return true;//放行
        }
        //2.对要登入的请求进行拦截
        UserDTO userDTO = (UserDTO) ThreadLocalUtil.get();
        if (Objects.isNull(userDTO)) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.fail("请先登录")));
            response.setStatus(401);
            return false;// 拦截
        }
        //有用户,则放行
        return true;//放行
    }


}
